import axios from 'axios'
import {
  MessageBox,
  Message,
  Loading
} from 'element-ui'
import store from '@/store'
import {
  getToken,
  removeToken
} from '@/utils/auth'
import router from '@/router'

// 创建一个axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 50000
})
let loadingInstance = Loading.service()
loadingInstance.close()
// 请求拦截
service.interceptors.request.use(
  config => {
    // 请求头设置
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    loadingInstance = Loading.service({
      fullscreen: true,
      text: '数据加载中,请稍等~',
      background: '#ffffff00'
    })
    // if (config.method == 'get' || config.method == 'GET') {
    //   for (let obj in config.params) {
    //     console.log(typeof config.params[obj])
    //     if (typeof config.params[obj] == 'string') {
    //       if (config.params[obj].indexOf('[') != -1) {
    //        config.params[obj]=config.params[obj].replace(/\[/g, '%5B')
    //        console.log(config.params[obj])
    //       }
    //     }
    //   }
    // }
    // console.log(config)
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截
service.interceptors.response.use(
  response => {
    const res = response.data
    loadingInstance.close()
    if (res.code !== '200') {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      if (res.code === 401 || res.code === 50012 || res.code === 50014) {
        MessageBox.confirm('您已经登出，您可以取消停留在此页面，或再次登录', '确认注销', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // router.push('/login')
          store.dispatch('user/resetToken').then(() => {
            localStorage.removeItem('menuInfo')
            localStorage.removeItem('routesList')
            removeToken()
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error)
    loadingInstance.close()
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
